<template>
  <div style="padding: 0 8px">
    <el-alert
      :title="
        props.type === 'PROJECT_BASE_FIELD'
          ? '用于管理配置项目列表需要的显示字段，支持配置多种业务字段类型，以及自定义项目列表的字段排序，配置后对所有项目生效。'
          : '用于管理任务列表需要的显示字段，支持配置多种业务字段类型，以及自定义任务列表的字段排序，配置后对所有任务列表生效。'
      "
      type="warning"
      :closable="false"
      style="margin-top: 8px"
    />
    <CToolbar
      :fields="fields"
      :visibleButtons="toolbarOptions"
      :search-fields="['name']"
      @openAddRecordDialog="handleAddField"
      @filter="handleFilter"
      style="position: relative; top: 0; left: 0; padding: 8px 0"
    >
      <template #toolbar-right-before>
        <el-input
          v-model="searchName"
          placeholder="输入关键词"
          class="search-input"
          :prefix-icon="Search"
          @change="handleSearch"
          style="margin-right: 6px"
        />
      </template>
    </CToolbar>
    <div class="wbs-tree-container">
      <!-- 批量操作浮层 -->
      <CLBatchOpToolbar
        :show="showCLBatchOpToolbar"
        :selected-count="selectedRecords.length"
        @delete="handleBatchDelete"
      ></CLBatchOpToolbar>

      <!--   表格   -->
      <CLTable
        v-loading="loading"
        :router-fields="['invisibleStatus']"
        :fields="fields"
        :initial-data="tableData"
        :line-height="currentLineHeight"
        :more-actions="moreActions"
        :tableConfig="tableConfig"
        @pagerChange="pagerChange"
        @onMoreAction="handleMoreAction"
        @show:records="handleShowRecords"
        @drag-completed="dragCompleted"
      >
      </CLTable>
      <!-- 字段配置悬浮层 -->
      <FieldConfigPopup
        :fields="currentFields"
        :position="fieldConfigPosition"
        :visible="showFieldConfig"
        @close="showFieldConfig = false"
        @fieldsChange="handleFieldsChange"
      />
    </div>
  </div>

  <!--  <CDialog-->
  <!--    :title="operate === 'create' ? '新建项目字段' : '编辑项目字段'"-->
  <!--    v-model="dialogVisible"-->
  <!--    @handleDialogOk="handleCreateOrEdit"-->
  <!--    :fields="dialogField"-->
  <!--    :nodeData="selectedNode"-->
  <!--  ></CDialog>-->
  <AddFieldDialog
    v-model="dialogVisible"
    :title="operate === 'create' ? '添加字段' : '修改字段'"
    @handleSubmit="handleCreateOrEdit"
    :originData="selectedNode"
  />
</template>

<script setup lang="ts">
  import AddFieldDialog from "@/views/pm/setting/baseInfo/AddFieldDialog.vue";
  import CLBatchOpToolbar from "@/components/CLBatchOpToolbar.vue";
  import CLTable from "@/components/CLTable/index.vue";
  import dist from "@/utils/dist.ts";
  import { ref, provide, reactive, onMounted } from "vue";
  import { DynamicField } from "@/data/wbsFields.ts";
  import { ElInput, ElMessage, ElMessageBox } from "element-plus";
  import {
    tableFields,
    dialogFields,
  } from "@/views/pm/globalSetting/baseFieldManagement/fields/index.ts";
  import FieldConfigPopup from "@/components/FieldConfigPopup.vue";
  import CDialog from "@/components/CDialog.vue";
  import { deepCopy } from "@/utils/common.ts";
  import type { pagerListQueryType } from "@/interface/common.ts";
  import { Search } from "@element-plus/icons-vue";
  import CToolbar from "@/components/CToolbar.vue";
  import {
    getDetailByTargetType,
    updateBaseField,
  } from "@/api/pm/baseFieldManagement.ts";
  import type {
    BaseDataConfigEntityRes,
    baseFieldVo,
  } from "@/interface/pm/baseFieldManagement.ts";

  interface Props {
    type: string;
  }
  const props = defineProps<Props>();

  const loading = ref(false);
  const searchName = ref("");
  const tableDataQuery = reactive<pagerListQueryType>({
    pageNo: 1,
    pageSize: 10,
    conditions: [],
  });

  // 批量操作
  const showCLBatchOpToolbar = ref(false);
  const selectedRecords = ref<any[]>([]);
  // 处理批量删除操作
  const handleBatchDelete = () => {
    console.log("selectedRecords", selectedRecords.value);
    if (selectedRecords.value.length === 0) return;
    ElMessageBox.confirm("确定删除该字段?", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      // type: "warning",
      draggable: true,
    })
      .then(async () => {
        const dataCopy = deepCopy(tableDataOrigin.value);
        const delSortArr = selectedRecords.value.map((item) => item.sort);
        const saveData = dataCopy.filter(
          (item) => !delSortArr.includes(item.sort),
        );
        const updateParams: BaseDataConfigEntityRes = {
          config: JSON.stringify(saveData),
          id: typeFieldsDetails.value.id,
          targetType: typeFieldsDetails.value.targetType,
        };
        await updateBaseField(updateParams);
        ElMessage({
          type: "success",
          message: "删除成功",
        });
        await getTableData();
      })
      .catch(() => {});
    // 删除完成后清空选中状态
  };

  // 表格
  const fields = ref<DynamicField[]>(tableFields); // table表格展示列
  const tableData = ref<baseFieldVo[]>([]);
  const tableDataOrigin = ref<baseFieldVo[]>([]);
  const typeFieldsDetails = ref<BaseDataConfigEntityRes>({});
  // 当前行高设置
  const currentLineHeight = ref<"low" | "medium" | "high" | "ultra-high">(
    "low",
  );
  const moreActions = ref([
    // { key: "setting", label: "配置类型" },
    { key: "edit", label: "编辑" },
    { key: "delete", label: "删除" },
  ]);
  const tableConfig = ref({
    editable: false,
    borderMode: "none",
    tableH: "calc(100vh - 222px)",
    showOperationsColumn: true, // 是否显示操作列
    OperationsColumnMode: "textIcon", // 操作列模式，text为文本模式
    // OperationsColumnWidth: 10, //自定义操作列宽度
    frozenColCount: 0, // 冻结前面列数
    rightFrozenColCount: 0, // 冻结后面列数
    page: {
      enable: false,
    },
    // tree: {
    //   enabled: true, // 开启树形结构
    //   column: 2, // 开启的树形结构的列索引
    //   mode: "wbs", // 开启wbs模式
    // },
    rowSeriesNumber: {
      dragOrder: true, // 开启行号拖拽排序
    },
    // borderMode: "none", // 表格边框模式，none为无边框
  });

  const pagerChange = (pager: { currentPage: number; pageSize: number }) => {
    tableDataQuery.pageNo = pager.currentPage;
    tableDataQuery.pageSize = pager.pageSize;
    getTableData();
  };

  const handleSearch = async () => {
    await getTableData();
    tableData.value = tableData.value.filter((item) =>
      item.displayName.includes(searchName.value),
    );
  };

  const handleMoreAction = async (action: string, node: any) => {
    if (action === "edit") {
      selectedNode.value = deepCopy(node);
      selectedNode.value.name = selectedNode.value?.name?.zh_CN;
      if (selectedNode.value.canModify === 0) {
        dialogFields.forEach((field) => {
          if (
            field.field === "uiType" ||
            field.field === "default" ||
            field.field === "required"
          ) {
            field.disable = true;
          }
        });
      }
      dialogVisible.value = true;
      operate.value = "edit";
    } else if (action === "delete") {
      ElMessageBox.confirm("确定删除该字段?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        draggable: true,
      })
        .then(async () => {
          const dataCopy = deepCopy(tableDataOrigin.value);
          const index = dataCopy.findIndex((item) => item.sort === node.sort);
          dataCopy.splice(index, 1);
          const updateParams: BaseDataConfigEntityRes = {
            config: JSON.stringify(dataCopy),
            id: typeFieldsDetails.value.id,
            targetType: typeFieldsDetails.value.targetType,
          };
          await updateBaseField(updateParams);
          ElMessage({
            type: "success",
            message: "删除成功",
          });
          await getTableData();
        })
        .catch(() => {});
    } else if (action === "invisibleStatus") {
      // console.log("invisibleStatus", node);
      loading.value = true;
      const copyTableData = deepCopy(tableDataOrigin.value);
      const item = copyTableData.find((item) => item.sort === node.sort);
      if (item) {
        item.invisible = item.invisible === 1 ? 0 : 1;
      }
      const updateParams: BaseDataConfigEntityRes = {
        config: JSON.stringify(copyTableData),
        id: typeFieldsDetails.value.id,
        targetType: typeFieldsDetails.value.targetType,
      };
      await updateBaseField(updateParams);
      ElMessage({
        type: "success",
        message: "修改成功",
      });
      await getTableData();
    }
  };
  const handleShowRecords = (records: any[]) => {
    console.log("handleShowRecords", records);
    selectedRecords.value = records;
    showCLBatchOpToolbar.value = records.length > 0;
  };
  const dragCompleted = async (dragData: {
    draggedId: number;
    targetId: number;
    position: string;
  }) => {
    console.log("dragCompleted", tableDataOrigin.value, dragData);

    return;
    const startIndex = tableDataOrigin.value.findIndex(
      (item) => item.idChain === dragData.draggedId,
    );
    const endIndex = tableDataOrigin.value.findIndex(
      (item) => item.idChain === dragData.targetId,
    );
    // const changeList = tableData.value.splice(startIndex, endIndex)
    const tablelist = deepCopy(tableDataOrigin.value);
    for (let i = 0; i < tablelist.length; i++) {
      if (startIndex === i) {
        tablelist[i].sort = tablelist[endIndex].sort;
        tablelist[i].idChain = tablelist[endIndex].sort;
      } else if (i > startIndex && i <= endIndex) {
        tablelist[i].sort -= 1;
        tablelist[i].idChain = tablelist[i].sort;
      }
    }
    const updateParams: BaseDataConfigEntityRes = {
      config: JSON.stringify(tablelist),
      id: typeFieldsDetails.value.id,
      targetType: typeFieldsDetails.value.targetType,
    };
    await updateBaseField(updateParams);
  };

  // 配置字段
  const currentFields = ref<DynamicField[]>([]);
  const fieldConfigPosition = ref({ left: 0, top: 0 });
  const showFieldConfig = ref(false);

  // 处理字段配置变化
  const handleFieldsChange = (updatedFields: DynamicField[]) => {
    // 更新本地字段配置，确保拖拽后能同步显示
    currentFields.value = JSON.parse(JSON.stringify(updatedFields));
    console.log("字段配置已更新:", updatedFields);
    fields.value = [...updatedFields];
  };

  // 显示字段配置弹窗
  const showFieldConfigPopup = (position: { left: number; top: number }) => {
    fieldConfigPosition.value = position;
    currentFields.value = JSON.parse(JSON.stringify(fields.value || []));
    setTimeout(() => {
      showFieldConfig.value = !showFieldConfig.value;
    }, 100);
  };
  // const addRecord = (newRecords: ProjectNode[]) => {
  //   tableData.value = [...newRecords];
  // };
  //
  // // 提供给所有子孙组件使用
  // provide("addRecord", addRecord);
  provide("showFieldConfigPopup", showFieldConfigPopup);

  // 弹框
  const dialogField = ref<DynamicField[]>(dialogFields);
  const dialogVisible = ref(false);
  const operate = ref("create");
  const selectedNode = ref<baseFieldVo>({} as baseFieldVo);

  const handleCreateOrEdit = async (formData: Record<string, any>) => {
    console.log(formData, "handleCreateLifecycle");
    if (operate.value === "create") {
      const params = {
        canModify: 1,
        code: "", // 不管
        displayName: formData.displayName,
        // isDisabled: formData.isDisabled,
        uiType: formData.uiType,
        default: formData.default,
        sort: tableDataOrigin.value.length + 1,
        type: "VARCHAR", // 不管
        required: formData.required ? formData.required : false,
        disableModify: formData.disableModify,
        invisible: 1,
        option: JSON.stringify(formData.option),
      };
      const tableDataList = deepCopy(tableDataOrigin.value);
      tableDataList.push(params);
      const updateParams: BaseDataConfigEntityRes = {
        config: JSON.stringify(tableDataList),
        id: typeFieldsDetails.value.id,
        targetType: typeFieldsDetails.value.targetType,
      };
      await updateBaseField(updateParams);
      ElMessage({
        type: "success",
        message: "添加成功",
      });
      dialogVisible.value = false;
      await getTableData();
    } else if (operate.value === "edit") {
      const dataCopy = deepCopy(tableDataOrigin.value);
      const currentItem = dataCopy.find((item) => item.sort === formData.sort);
      if (currentItem) {
        currentItem.displayName = formData.displayName;
        currentItem.uiType = formData.uiType;
        currentItem.required = formData.required;
        currentItem.disableModify = formData.disableModify;
        currentItem.option = JSON.stringify(formData.option);
        const updateParams: BaseDataConfigEntityRes = {
          config: JSON.stringify(dataCopy),
          id: typeFieldsDetails.value.id,
          targetType: typeFieldsDetails.value.targetType,
        };
        await updateBaseField(updateParams);
        ElMessage({
          type: "success",
          message: "编辑成功",
        });
        dialogVisible.value = false;
        await getTableData();
      }
    }
  };

  // 工具栏选项
  const toolbarOptions = ref({
    add: {
      name: "新增",
      enable: true,
    },
    fieldConfig: false,
    filter: false,
    sort: false,
    lineHeight: false,
    help: false,
    log: false,
    export: false,
    search: false,
  });
  // 处理筛选事件
  const handleFilter = (condition: string, direction: "asc" | "desc") => {
    console.log("筛选条件:", condition, "排序方向:", direction);
  };

  const handleAddField = () => {
    dialogVisible.value = true;
    operate.value = "create";
  };
  const getTableData = async () => {
    loading.value = true;
    const res = await getDetailByTargetType(props.type);
    loading.value = false;
    // console.log("res", JSON.parse(res.config || "[]"));
    // console.log("list", JSON.parse(res.config || "[]"));
    selectedRecords.value = [];
    tableDataOrigin.value = JSON.parse(res.config || "[]");
    tableData.value = JSON.parse(res.config || "[]").map(
      (item: baseFieldVo) => {
        item.requiredName = item.required ? "必填" : "非必填";
        item.invisibleStatus = item.invisible === 1;
        item.id = item.sort;
        item.idChain = item.sort;
        item.typexName = fieldsTypeMap[item.uiType];
        item.canOperate = item.canModify === 0;
        item.isDisabled = item.disableModify ? "是" : "否";
        return item;
      },
    ) as baseFieldVo[];
    tableData.value = tableData.value.sort((a, b) => a.sort - b.sort);
    console.log(tableData.value, "list", tableDataOrigin.value);
    typeFieldsDetails.value = res;
  };
  const fieldsTypeMap: any = {};
  onMounted(async () => {
    const fieldDist = await dist.getDictData("sdm.global.defined.filedType");
    fieldDist.items.map((item) => {
      fieldsTypeMap[item.code] = item.displayName;
    });
    getTableData();
  });
</script>

<style scoped lang="scss">
  .wbs-tree-container {
    background-color: #fff;
    position: relative;
    .table-container {
      margin-top: 8px;
      height: calc(100vh - 200px);
    }
  }
</style>
